<template>
  <div class="user-management">
    <div class="page-header">
      <h2>用户管理</h2>
      <button class="btn btn-primary" @click="loadUsers">🔄 刷新</button>
    </div>

    <!-- 筛选器 -->
    <div class="card filters">
      <div class="filter-group">
        <label>用户类型：</label>
        <select v-model="filters.is_guest" @change="loadUsers">
          <option value="">全部</option>
          <option value="0">正式用户</option>
          <option value="1">游客</option>
        </select>
      </div>

      <div class="filter-group">
        <label>状态：</label>
        <select v-model="filters.status" @change="loadUsers">
          <option value="">全部</option>
          <option value="1">正常</option>
          <option value="0">禁用</option>
        </select>
      </div>

      <div class="filter-group">
        <label>关键词：</label>
        <input 
          v-model="filters.keyword" 
          type="text" 
          placeholder="用户名/昵称/手机号"
          @keyup.enter="loadUsers"
        />
      </div>

      <button class="btn btn-primary" @click="loadUsers">搜索</button>
    </div>

    <!-- 用户表格 -->
    <div class="card">
      <div v-if="loading" class="loading">加载中...</div>
      
      <div v-else-if="users.length === 0" class="empty">
        暂无用户数据
      </div>

      <div v-else>
        <table>
          <thead>
            <tr>
              <th>ID</th>
              <th>用户名</th>
              <th>昵称</th>
              <th>手机号</th>
              <th>类型</th>
              <th>状态</th>
              <th>注册时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in users" :key="user.id">
              <td>{{ user.id }}</td>
              <td>{{ user.username || '-' }}</td>
              <td>{{ user.nickname }}</td>
              <td>{{ user.phone || '-' }}</td>
              <td>
                <span :class="['status-tag', user.is_guest ? 'status-cancelled' : 'status-paid']">
                  {{ user.is_guest ? '游客' : '正式用户' }}
                </span>
              </td>
              <td>
                <span :class="['status-tag', user.status === 1 ? 'status-paid' : 'status-cancelled']">
                  {{ user.status === 1 ? '正常' : '禁用' }}
                </span>
              </td>
              <td>{{ formatDate(user.created_at) }}</td>
              <td>
                <div class="actions">
                  <button class="btn btn-default btn-sm" @click="viewUser(user)">
                    详情
                  </button>
                  <button 
                    class="btn btn-sm"
                    :class="user.status === 1 ? 'btn-danger' : 'btn-primary'"
                    @click="toggleUserStatus(user)"
                  >
                    {{ user.status === 1 ? '禁用' : '启用' }}
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- 分页 -->
        <div class="pagination">
          <button 
            class="btn btn-default"
            :disabled="currentPage <= 1"
            @click="changePage(currentPage - 1)"
          >
            上一页
          </button>
          <span>第 {{ currentPage }} / {{ totalPages }} 页（共 {{ total }} 条）</span>
          <button 
            class="btn btn-default"
            :disabled="currentPage >= totalPages"
            @click="changePage(currentPage + 1)"
          >
            下一页
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { getUsers, updateUserStatus } from '../api/user';

const users = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const filters = ref({
  is_guest: '',
  status: '',
  keyword: ''
});

const totalPages = computed(() => Math.ceil(total.value / pageSize.value));

const loadUsers = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    };
    
    // 只添加有值的筛选条件
    if (filters.value.status !== '') {
      params.status = filters.value.status;
    }
    if (filters.value.is_guest !== '') {
      params.is_guest = filters.value.is_guest;
    }
    if (filters.value.keyword) {
      params.keyword = filters.value.keyword;
    }

    const res = await getUsers(params);
    console.log('用户列表响应:', res); // 调试日志
    if (res.success) {
      users.value = res.data.list || [];
      total.value = res.data.total || 0;
    } else {
      alert(res.message || '加载失败');
    }
  } catch (error) {
    console.error('加载用户失败:', error);
    alert('网络错误: ' + (error.message || '未知错误'));
  } finally {
    loading.value = false;
  }
};

const changePage = (page) => {
  currentPage.value = page;
  loadUsers();
};

const formatDate = (dateStr) => {
  if (!dateStr) return '-';
  return dateStr.replace('T', ' ').substring(0, 19);
};

const viewUser = (user) => {
  alert(`用户详情\nID: ${user.id}\n用户名: ${user.username}\n昵称: ${user.nickname}\n手机号: ${user.phone || '未绑定'}`);
};

const toggleUserStatus = async (user) => {
  const newStatus = user.status === 1 ? 0 : 1;
  const confirmMsg = newStatus === 0 ? '确定要禁用该用户吗？' : '确定要启用该用户吗？';
  
  if (!confirm(confirmMsg)) return;

  try {
    const res = await updateUserStatus(user.id, newStatus);

    if (res.success) {
      alert('操作成功');
      loadUsers();
    } else {
      alert(res.message || '操作失败');
    }
  } catch (error) {
    console.error('更新用户状态失败:', error);
    alert('网络错误: ' + (error.message || '未知错误'));
  }
};

onMounted(() => {
  loadUsers();
});
</script>

<style scoped>
.user-management {
  max-width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.filters {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group label {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}

.actions {
  display: flex;
  gap: 8px;
}

.btn-sm {
  padding: 4px 12px;
  font-size: 12px;
}
</style>

